package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.port.fee.common.Result;
import com.port.fee.dto.CustomerDTO;
import com.port.fee.entity.Customer;
import com.port.fee.service.CustomerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户管理控制器
 */
@RestController
@RequestMapping("/customer")
@Tag(name = "客户管理", description = "客户相关接口")
public class CustomerController {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerService customerService;

    /**
     * 获取客户详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取客户详情", description = "根据客户ID获取详情")
    public Result<Customer> getInfo(@PathVariable("id") Long id) {
        Customer customer = customerService.getCustomerById(id);
        if (customer != null) {
            return Result.success(customer);
        } else {
            return Result.failed("客户不存在");
        }
    }
    
    /**
     * 添加默认客户（用于测试）
     */
    @PostMapping("/default")
    @Operation(summary = "添加默认客户", description = "添加一个默认客户用于测试")
    public Result<Long> addDefault() {
        Long customerId = customerService.addDefaultCustomer();
        return Result.success(customerId, "添加默认客户成功");
    }
    
    /**
     * 分页查询客户列表
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询客户列表", description = "根据条件分页查询客户列表")
    public Result<Map<String, Object>> list(@RequestBody CustomerDTO customerDTO) {
        try {
            // 转换对象
            Customer customer = new Customer();
            BeanUtils.copyProperties(customerDTO, customer);
            
            // 默认值处理
            int pageNum = customerDTO.getPageNum() == null ? 1 : customerDTO.getPageNum();
            int pageSize = customerDTO.getPageSize() == null ? 10 : customerDTO.getPageSize();
            
            // 分页查询
            Page<Customer> page = customerService.listCustomers(customer, pageNum, pageSize);
            
            // 封装返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("records", page.getRecords());
            data.put("total", page.getTotal());
            data.put("pages", page.getPages());
            data.put("current", page.getCurrent());
            data.put("size", page.getSize());
            
            return Result.success(data);
        } catch (Exception e) {
            LOGGER.error("查询客户列表异常: ", e);
            return Result.failed("查询客户列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 新增客户
     */
    @PostMapping
    @Operation(summary = "新增客户", description = "新增客户信息")
    public Result<Void> add(@RequestBody CustomerDTO customerDTO) {
        try {
            LOGGER.info("添加客户请求参数: {}", customerDTO);
            
            // 验证必要参数
            if (customerDTO.getCustomerName() == null || customerDTO.getCustomerName().trim().isEmpty()) {
                return Result.failed("客户名称不能为空");
            }
            
            Customer customer = new Customer();
            BeanUtils.copyProperties(customerDTO, customer);
            
            // 设置默认值
            if (customer.getCustomerType() == null) {
                customer.setCustomerType(1); // 默认类型
            }
            
            customer.setCreateTime(new Date());
            customer.setUpdateTime(new Date());
            
            if (customerService.addCustomer(customer)) {
                return Result.success(null, "新增成功");
            } else {
                return Result.failed("新增失败，可能客户编号已存在");
            }
        } catch (Exception e) {
            LOGGER.error("添加客户异常: ", e);
            return Result.failed("添加客户失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改客户
     */
    @PutMapping
    @Operation(summary = "修改客户", description = "修改客户信息")
    public Result<Void> update(@RequestBody CustomerDTO customerDTO) {
        try {
            if (customerDTO.getCustomerId() == null) {
                return Result.failed("客户ID不能为空");
            }
            
            Customer customer = new Customer();
            BeanUtils.copyProperties(customerDTO, customer);
            
            if (customerService.updateCustomer(customer)) {
                return Result.success(null, "修改成功");
            } else {
                return Result.failed("修改失败，可能客户编号已存在");
            }
        } catch (Exception e) {
            LOGGER.error("修改客户异常: ", e);
            return Result.failed("修改客户失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除客户
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除客户", description = "根据ID删除客户")
    public Result<Void> delete(@PathVariable("id") Long id) {
        try {
            if (customerService.deleteCustomer(id)) {
                return Result.success(null, "删除成功");
            } else {
                return Result.failed("删除失败，客户不存在或已被引用");
            }
        } catch (Exception e) {
            LOGGER.error("删除客户异常: ", e);
            return Result.failed("删除客户失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查客户编号是否已存在
     */
    @GetMapping("/check/{code}")
    @Operation(summary = "检查客户编号", description = "检查客户编号是否已存在")
    public Result<Boolean> checkCustomerCode(@PathVariable("code") String code, @RequestParam(required = false) Long excludeId) {
        boolean exists = customerService.checkCustomerCodeExists(code, excludeId);
        return Result.success(exists);
    }
} 